package muhtar.application;

import java.util.HashMap;
import java.util.Map;

import muhtar.common.MuhtarConstants;
import muhtar.controller.RequestHandler;

import org.eclipse.jetty.server.Server;

import com.hazelcast.core.Hazelcast;

public class MuhtarApplication  
{
	private Map<String, Object> parameters;
	private RequestHandler requestHandler;

	private void showAbout() {
		System.out.println("Muhtar Configuration Server");
		System.out.println("copyleft (c) 2011 jurfa.com");
		System.out.println("starting service...");
	}
	
	private void showHelp() {
		System.out.println("usage: ");
		System.out.println("\t-p <PORT>");
		System.out.println();
		System.out.println("example:");
		System.out.println("\tjava -jar muhtar.jar -p 9090");
	}

	private void loadDefaultParameters() 
	{
		parameters = new HashMap<String, Object>();
		parameters.put(MuhtarConstants.PARAMETER_PORT, MuhtarConstants.DEFAULT_PORT);
	}
	
	private void extractParameters(String[] args) 
	{
		for (int i = 0; i < args.length; i++) {
			if (args[i].startsWith("-") && i < args.length) {
				parameters.put(args[i], args[i+1]);
			}
		}
	}
	
	private void connectServer(int port) throws Exception
	{
		Server server = null;
		try {
			server = new Server(port);
			server.setHandler(requestHandler);
			server.start();
			server.join();
		} finally {
			if (server != null) {
				server.stop();
			}
		}
	}
	
	private void runServer() throws Exception 
	{
		// create request handler
		requestHandler = new RequestHandler();
		
		int port = Integer.parseInt(parameters.get(MuhtarConstants.PARAMETER_PORT).toString());
		int tryCount = port == MuhtarConstants.DEFAULT_PORT ? 5 : 0;
		
		do {
			try {
				connectServer(port);
			} catch (Exception e) {
				System.out.println("could not connect port: " + port++);
			}			
		} while (tryCount-- > 0);
		
		Hazelcast.shutdown();
	}
	
	public void execute(String[] args) throws Exception 
	{
		showAbout();
		
		if (args.length == 1) {
			String[] helpCommands = {"--help", "-help", "-h"};
			for (String helpCommand : helpCommands) {
				if (helpCommand.equals(args[0])) {
					showHelp();
					return;					
				}
			}
		}
		
		loadDefaultParameters();
		extractParameters(args);
		runServer();
	}
	
	public static void main(String[] args) throws Exception {
		new MuhtarApplication().execute(args);
	}
}
